package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.MemberAddr;
import com.powernode.mapper.MemberAddrMapper;
import com.powernode.service.MemberAddrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.MemberAddrServiceImpl")
public class MemberAddrServiceImpl extends ServiceImpl<MemberAddrMapper, MemberAddr> implements MemberAddrService{

    @Autowired
    private MemberAddrMapper memberAddrMapper;

    @Override
    @Cacheable(key = "#openId")
    public List<MemberAddr> queryMemberAddrListByOpenId(String openId) {
        return memberAddrMapper.selectList(new LambdaQueryWrapper<MemberAddr>()
                .eq(MemberAddr::getOpenId,openId)
                .orderByDesc(MemberAddr::getCommonAddr,MemberAddr::getCreateTime)
        );
    }

    /**
     * 会员必须得有一个默认收货地址
     * 也就是说：会员新增的第一个地址一定是默认收货地址
     * @param memberAddr
     * @return
     */
    @Override
    @CacheEvict(key = "#memberAddr.openId")
    public Boolean saveMemberAddr(MemberAddr memberAddr) {
        memberAddr.setCommonAddr(0);
        memberAddr.setStatus(1);
        memberAddr.setCreateTime(new Date());
        memberAddr.setUpdateTime(new Date());

        // 查询当前会员的收货地址
        Long count = memberAddrMapper.selectCount(new LambdaQueryWrapper<MemberAddr>()
                .eq(MemberAddr::getOpenId, memberAddr.getOpenId())
        );
        // 判断会员是否有收货地址
        if (0 == count) {
            // 说明：当前会员没有收货地址，所以新增的地址为默认收货地址
            memberAddr.setCommonAddr(1);
        }
        return memberAddrMapper.insert(memberAddr)>0;
    }

    @Override
    @CacheEvict(key = "#memberAddr.openId")
    public Boolean modifyMemberAddr(MemberAddr memberAddr) {
        memberAddr.setUpdateTime(new Date());
        return memberAddrMapper.updateById(memberAddr)>0;
    }

    @Override
    @CacheEvict(key = "#openId")
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeMemberAddrByAddrId(String openId, Long addrId) {
        // 查询当前会员默认收货地址
        MemberAddr oldDefaultMemberAddr = memberAddrMapper.selectOne(new LambdaQueryWrapper<MemberAddr>()
                .eq(MemberAddr::getOpenId, openId)
                .eq(MemberAddr::getCommonAddr, 1)
        );
        // 判断删除的收货地址与默认收货地址是否一致
        if (oldDefaultMemberAddr.getAddrId() == addrId) {
            // 说明：当前删除的收货地址为默认收货地址，需要重新设置一个新的默认收货地址（最近添加的收货地址）
            // 查询当前会员的非默认收货地址列表
            List<MemberAddr> memberAddrList = memberAddrMapper.selectList(new LambdaQueryWrapper<MemberAddr>()
                    .eq(MemberAddr::getOpenId, openId)
                    .eq(MemberAddr::getCommonAddr, 0)
                    .orderByDesc(MemberAddr::getCreateTime)
            );
            // 判断非默认收货地址是否有值
            if (!CollectionUtils.isEmpty(memberAddrList) && memberAddrList.size() != 0) {
                // 获取非默认的收货地址并设置为新的默认收货地址
                MemberAddr newDefaultMemberAddr = memberAddrList.get(0);
                newDefaultMemberAddr.setCommonAddr(1);
                memberAddrMapper.updateById(newDefaultMemberAddr);
            }
        }
        // 删除指定的收货地址
        return memberAddrMapper.deleteById(addrId)>0;
    }

    @Override
    @CacheEvict(key = "#openId")
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyMemberDefaultAddr(String openId, Long newAddrId) {
        // 查询用户原来的默认收货地址
        MemberAddr oldDefaultMemberAddr = memberAddrMapper.selectOne(new LambdaQueryWrapper<MemberAddr>()
                .eq(MemberAddr::getOpenId, openId)
                .eq(MemberAddr::getCommonAddr, 1)
        );
        // 判断新的默认与旧的默认是否一致
        if (oldDefaultMemberAddr.getAddrId() == newAddrId) {
            return true;
        }
        // 将原来默认收货地址修改为非默认收货地址
        oldDefaultMemberAddr.setCommonAddr(0);
        memberAddrMapper.updateById(oldDefaultMemberAddr);

        // 设置新的默认收货地址
        MemberAddr newDefaultMemberAddr = new MemberAddr();
        newDefaultMemberAddr.setAddrId(newAddrId);
        newDefaultMemberAddr.setCommonAddr(1);
        return memberAddrMapper.updateById(newDefaultMemberAddr)>0;
    }
}
